// renderjs 环境下的 XLSX 导入
let XLSX
try {
  // 尝试使用 require 方式导入（renderjs 环境通常支持）
  XLSX = require('xlsx')
  console.log('XLSX 通过 require 导入成功')
} catch (e) {
  console.error('XLSX require 导入失败:', e)
  // 如果 require 失败，尝试其他方式
  try {
    // 尝试从全局对象获取
    XLSX = window.XLSX || global.XLSX
    if (XLSX) {
      console.log('XLSX 从全局对象获取成功')
    } else {
      console.error('全局对象中未找到 XLSX')
    }
  } catch (e2) {
    console.error('获取全局 XLSX 失败:', e2)
  }
}

export default {
  data() {
    return {
      exportData: [], // 导出数据 [{key:value}]
      exportName: '', // 导出名字 string
      exportConfig: {}, // 暂时未使用
      hideTimeName: false, // 导出名字是否隐藏时间戳
      sheetNameList: [], //表头名字 ['string'],不传则取exportData key
    }
  },

  methods: {
    timestampToDate(timestamp) {
      const date = new Date(timestamp)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      return `${year}${month}${day}${hours}${minutes}`
    },
    exportExcel(event, ownerInstance) {
      try {
        console.log('=== exportExcel 开始执行 ===')
        console.log('XLSX 对象:', XLSX)
        console.log('exportData 长度:', this.exportData.length)
        
        // 检查 XLSX 是否可用
        if (!XLSX) {
          console.error('XLSX 未定义，无法执行导出')
          if (ownerInstance && ownerInstance.callMethod) {
            ownerInstance.callMethod('exportOver', 'XLSX 未定义，导出失败')
          }
          return
        }
        
        if (this.exportData.length === 0) {
          console.log('导出数据为空')
          return
        }
        
        let fileName = `${this.exportName || '默认导出名字'}${
          !this.hideTimeName ? this.timestampToDate(new Date()) : ''
        }.xlsx`
        
        console.log('文件名:', fileName)
        console.log('开始创建 Excel 工作表...')
        
        let sheet = XLSX.utils.json_to_sheet(this.exportData)
        XLSX.utils.sheet_add_aoa(sheet, [this.sheetNameList], {
          origin: 'A1',
        })
        const workbook = XLSX.utils.book_new()
        XLSX.utils.book_append_sheet(workbook, sheet, 'Sheet1')
        
        console.log('开始写入 Excel 文件...')
        const arrBufferData = XLSX.write(workbook, {
          bookType: 'xlsx',
          type: 'array',
        })
        
        let blobData = new Blob([arrBufferData], {
          type: 'application/octet-stream',
        })
        
        console.log('开始读取文件为 base64...')
        const reader = new FileReader()
        reader.readAsDataURL(blobData)
        reader.onload = (evt) => {
          console.log('文件读取完成，开始保存...')
          this.base64Data = evt.target.result
          this.base64Data = this.base64Data.replace(
            /^data:\S+\/\S+;base64,/,
            ''
          )
          let that = this
          that.ownerInstance = ownerInstance
          
          console.log('开始保存到设备...')
          plus.io.requestFileSystem(plus.io.PUBLIC_DOWNLOADS, function (fs) {
            let root = fs.root
            root.getFile(
              fileName,
              {
                create: true,
              },
              (fileEntry) => {
                fileEntry.createWriter(
                  (writer) => {
                    // 写入文件成功完成的回调函数 exportOver
                    writer.onwrite = (e) => {
                      console.log('文件保存成功:', e.target.fileName)
                      that.ownerInstance.callMethod(
                        'exportOver',
                        e.target.fileName
                      )
                    }
                    writer.writeAsBinary(that.base64Data)
                  },
                  (err) => {
                    console.error('创建文件写入器错误:', err)
                  }
                )
              },
              (err) => {
                console.error('创建文件错误:', err)
              }
            )
          })
        }
        
        reader.onerror = (error) => {
          console.error('文件读取错误:', error)
        }
        
      } catch (error) {
        console.error('exportExcel 执行错误:', error)
        if (ownerInstance && ownerInstance.callMethod) {
          ownerInstance.callMethod('exportOver', '导出失败: ' + error.message)
        }
      }
    },
    getExportData(val) {
      console.log('=== getExportData 被调用 ===')
      console.log('接收到的数据:', val)
      
      this.exportData = val.exportData || []
      this.exportName = val.exportName || ''
      this.exportConfig = val.exportConfig || {}
      this.hideTimeName = val.hideTimeName || false
      this.sheetNameList = val.sheetNameList || []
      
      console.log('设置后的数据:')
      console.log('- exportData 长度:', this.exportData.length)
      console.log('- exportName:', this.exportName)
      console.log('- sheetNameList:', this.sheetNameList)
      console.log('- hideTimeName:', this.hideTimeName)
    },
  },
}
